﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Mvc;
using ClassRoom.Models;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using WebGrease.Css.Extensions;

namespace ClassRoom.Controllers
{
    public class ApiController : Controller
    {
        public ActionResult Statistic()
        {
            var dbAccess = new DbAccess();
            var data = dbAccess.GetStatistic(System.Web.HttpContext.Current.Session["currentUserId"].ToString());

            var result = new
            {
                totalAction = data["totalAction"].AsDouble,
                totalLogin = data["totalLogin"].AsDouble,
                totalPost = data["totalPost"].AsDouble,
                totalComment = data["totalComment"].AsDouble
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            return Json(new { Msg = "Hello" }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult CheckLogin()
        {
            return Json(new
            {
                userId = System.Web.HttpContext.Current.Session["currentUserId"],
                userName = System.Web.HttpContext.Current.Session["currentUserName"],
                userType = System.Web.HttpContext.Current.Session["currentUserType"]
            }, JsonRequestBehavior.AllowGet);
        }
        private long UnixTimeNow()
        {
            var timeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
            return (long)timeSpan.TotalSeconds;
        }

        [HttpPost]
        public JsonResult SaveProject(ProjectModel project)
        {
            var dbAccess = new DbAccess();
            dbAccess.SaveProject(System.Web.HttpContext.Current.Session["currentUserId"].ToString(),
                project._id, project.name, project.desc, project.file, project.student, project.supervisor, project.secondMarker);

            return Json(new ResultModel
            {
                Code = 1
            }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public async Task<JsonResult> Login(UserModel loginModel)
        {
            //Stream req = Request.InputStream;
            //req.Seek(0, System.IO.SeekOrigin.Begin);
            //string json = new StreaReader(req).ReadToEnd();
            var dbAccess = new DbAccess();
            var user = dbAccess.FindOne(Query.And(Query.EQ("user", loginModel.user), Query.EQ("pwd", loginModel.pwd)));
            var result = new ResultModel();
            if (user != null)
            {
                System.Web.HttpContext.Current.Session["currentUserId"] = user["_id"].AsObjectId.ToString();
                System.Web.HttpContext.Current.Session["currentUserName"] = user["user"].AsString;
                System.Web.HttpContext.Current.Session["currentUserType"] = user["type"].AsDouble;
                result.Code = 1;
                result.Data = new
                {
                    userId = user["_id"].AsObjectId.ToString(),
                    username = user["user"].AsString,
                    userType = user["type"].AsDouble
                };
                dbAccess.WriteLog(new LogModel
                {
                    agentId = result.Data.userId,
                    type = 1,
                    time = UnixTimeNow()
                });
            }
            else
            {
                result.Code = -1;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult People()
        {
            var name = System.Web.HttpContext.Current.Request.QueryString["name"];
            var peopleType = System.Web.HttpContext.Current.Request.QueryString["peopleType"];
            var dbAccess = new DbAccess();
            var users = dbAccess.Find(Query.Matches("user", name));
            var result = new ResultModel();
            if (users != null)
            {
                var data = new List<object>();
                users.ForEach(i => data.Add(new
                {
                    userId = i["_id"].AsObjectId.ToString(),
                    userName = i["user"].AsString,
                    userType = i["type"].AsDouble,
                }));
                result.Data = data;
            }
            else
            {
                result.Code = -1;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Logout()
        {
            System.Web.HttpContext.Current.Session.Clear();
            return Json(new { }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult CreatePost(MsgModel msgModel)
        {
            //Stream req = Request.InputStream;
            //req.Seek(0, System.IO.SeekOrigin.Begin);
            //string json = new StreaReader(req).ReadToEnd();
            var dbAccess = new DbAccess();
            dbAccess.CreateNewPost(System.Web.HttpContext.Current.Session["currentUserId"].ToString(), msgModel.to, msgModel.content);

            return Json(new ResultModel
            {
                Code = 1
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetPosts()
        {
            var dbAccess = new DbAccess();
            var sessionUserId = System.Web.HttpContext.Current.Session["currentUserId"];
            var messages = dbAccess.GetPosts(sessionUserId != null ? sessionUserId.ToString() : string.Empty);

            var result = new List<object>();
            messages.AsBsonArray.ForEach(m =>
            {
                var mess = new
                {
                    _id = m["_id"].AsObjectId.ToString(),
                    from = m["from"].AsObjectId.ToString(),
                    to = m["to"].AsObjectId.ToString(),
                    content = m["content"].AsString,
                    comments = new List<object>()
                };
                m["comments"].AsBsonArray.ForEach(i =>
                {
                    var from = new
                    {
                        _id = i["from"]["_id"].AsObjectId.ToString(),
                        userName = i["from"]["user"].AsString,
                        userType = i["from"]["type"].AsDouble
                    };
                    var connemt = new
                    {
                        from,
                        content = i["content"].AsString
                    };
                    mess.comments.Add(connemt);
                });
                result.Add(mess);
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult PushComment(MsgModel msgModel)
        {
            var fromUserId = System.Web.HttpContext.Current.Session["currentUserId"].ToString();

            var dbAccess = new DbAccess();
            dbAccess.PushCommentToPost(fromUserId, msgModel);

            return Json(new ResultModel
            {
                Code = 1
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetProjects()
        {
            var dbAccess = new DbAccess();
            var sessionUserId = System.Web.HttpContext.Current.Session["currentUserId"];
            var projects = dbAccess.GetProjects(sessionUserId != null ? sessionUserId.ToString() : string.Empty);

            var result = new List<object>();
            projects.AsBsonArray.ForEach(m =>
            {
                var project = new
                {
                    _id = m["_id"].AsString,
                    name = m["name"].AsBsonValue != BsonNull.Value ? m["name"].AsString : string.Empty,
                    desc = m["desc"].AsBsonValue != BsonNull.Value ? m["desc"].AsString : string.Empty,
                    file = m["file"].AsBsonValue != BsonNull.Value ? m["file"].AsString : string.Empty,
                    student = m["student"].AsBsonValue != BsonNull.Value ? m["student"].AsString : string.Empty,
                    supervisor = m["supervisor"].AsBsonValue != BsonNull.Value ? m["supervisor"].AsString : string.Empty,
                    secondMarker = m["secondMarker"].AsBsonValue != BsonNull.Value ? m["secondMarker"].AsString : string.Empty,
                    studentName = m["studentName"].AsBsonValue != BsonNull.Value ? m["studentName"].AsString : string.Empty,
                    supervisorName = m["superVisorName"].AsBsonValue != BsonNull.Value ? m["superVisorName"].AsString : string.Empty,
                    secondMarkerName = m["secondMarkerName"].AsBsonValue != BsonNull.Value ? m["secondMarkerName"].AsString : string.Empty
                };
                result.Add(project);
            });

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
